﻿using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using UnityEngine;
namespace ChenYiZh
{
    public class Networking : Singleton<Networking>
    {
        [SerializeField, Range(1024, 49151)]
        ushort sendPort;
        [SerializeField, Range(1024, 49151)]
        ushort receivePort;
#if UNITY_EDITOR
        [SerializeField]
        bool LogReceive = false;
        [SerializeField]
        bool LogAllReceive = false;
        [SerializeField]
        bool LogSend = false;
#endif

        public delegate void Receive(NetworkMsg result);

        public static Receive Receives;
        private new void Awake()
        {
            base.Awake();
            UDPNetwork.Init(sendPort, receivePort, this);
        }

        public static void Send(NetworkMsg msg)
        {
#if UNITY_EDITOR
            if (Instance.LogSend)
                Debug.Log(string.Format("Send From {0} and msg from class {1} to class {2}.\nThe type is {3}.", msg.ClientID, msg.Sign.FromClass, msg.Sign.ToClass, msg.Sign.Type.ToString()));
#endif
            UDPNetwork.Send(msg.ToByte());
        }

        public void ReceiveHandler(byte[] data)
        {
            NetworkMsg result = NetworkMsg.ToMsg(data);
#if UNITY_EDITOR
            if (Instance.LogAllReceive)
                Debug.Log(string.Format("Receive From {0} and msg from class {1} to class {2}.\nThe type is {3}.", result.ClientID, result.Sign.FromClass, result.Sign.ToClass, result.Sign.Type.ToString()));
#endif
            if (!result.ClientID.Equals(ClientID))
            {
#if UNITY_EDITOR
                if (Instance.LogReceive)
                    Debug.Log(string.Format("Receive From {0} and msg from class {1} to class {2}.\nThe type is {3}.", result.ClientID, result.Sign.FromClass, result.Sign.ToClass, result.Sign.Type.ToString()));
#endif
                Receives(result);
            }
        }

        public static ushort SEND_PORT
        {
            get { return Instance.sendPort; }
            set { Instance.sendPort = value; }
        }

        public static ushort RECEIVE_PORT
        {
            get { return Instance.receivePort; }
            set { Instance.receivePort = value; }
        }

        private new void OnDestroy()
        {
            base.OnDestroy();
            UDPNetwork.Close();
        }

        public static string ClientID
        {
            get
            {
                string ip = Dns.GetHostName();
                foreach (IPAddress ipAddr in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                    if (ipAddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        ip = ipAddr.ToString();
                return ip;
            }
        }
    }
}
